/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-09-18 09:25:55
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-19 09:09:30
 * @FilePath: \keep_motion_api\controllers\sys\file.controller.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const { File } = require('@/models/sys');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置 multer 存储引擎
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const model = File.getModelName(req.params.module);
    const uploadDir = path.join('./uploads', model);
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, `${Date.now()}${ext}`);
  }
});
const upload = multer({ storage: storage });


const uploadFile =  async (req, res) => {
  try {
      upload.single('file')(req, res, async (err) => {
        if (err) {
          return res.status(500).json({ message: '文件上传失败', error: err });
        }
        const file = req.file;
        if (!file) {
          return res.status(400).json({ message: '未上传文件' });
        }
        const moduleName = File.getModelName(req.params.module);
        res.status(200).send({message:'文件上传成功',file:`/uploads/${moduleName}/${file.filename}`});
      });
    } catch (error) {
      res.status(500).json({ message: '文件上传失败', error });
    }
}

module.exports = {
  uploadFile
}